<template>
	<view style="width: 100vw;height: 100vh;overflow-y: scroll;background: #fff;">
		<HeaderBar v-if="!isIndex" />
		<image :src="ossUrl + `/static/27.png`" mode="widthFix" class="bgcard"></image>
		<view class="titlecard">领取我的名片</view>
		<view class="formcard">
			<view class="form-listcard" v-if="list.length === 0">
				<view class="form-list-inputcard">
					<input type="text" placeholder="我的姓名" placeholder-class="ac" v-model="form.nickname" />
				</view>
			</view>
			<!-- <view class="form-listcard" @click="open">
				<view class="form-list-inputcard">
					<input type="textcard" placeholder="我的领域" placeholder-class="ac" :disabled="true"
						v-model="identity.name" />
				</view>
				<image :src="ossUrl + `/static/28.png`" mode=""></image>
			</view> -->
			<view class="form-listcard">
				<view class="form-list-inputcard">
					<input type="text" placeholder="我当前的公司" placeholder-class="accard" v-model="form.company" />
				</view>
			</view>
		</view>
		<view class="btnsCard" @click="submit">立即领取</view>
		<ElectPopup ref="selectRef" v-model="identity" />

		<l-painter :board="template" style="width: 100%;" ref="painterRef" custom-style="position: fixed; left: 200%" />
		<card class="hb-img" style="position: fixed; left: 300%;top:-100%;width: 690rpx;" ref="cardRef" />
		<btnlogin :zheshow='zheshow' ref="btnlogin" @submit="submitLogin" />
	</view>
</template>

<script>
	import ElectPopup from './components/selectPopup/selectPopup.vue'
	import HeaderBar from "@/components/header/header.vue";
	import {
		InformationIdentity,
		InformationEditBusinessCard,
		InformationUserBusinessCardHeadData,
		InformationStyleSaving,
		InformationShareStylesSaving,
		InformationBusinessCardList,
		miniLogin,
		InformationUserInfo,
		InformationUserCodeLogin
	} from '@/common/http/api.js'
	import btnlogin from '@/components/login/butlogin.vue';
	import {
		uploadImg,
		uploadVideo,
		uploadDel
	} from '@/common/upload.js'
	import {
		ossUpload,
		ossDel
	} from '@/common/oss.js'
	import {
		url
	} from '../../common/config';
	export default {
		components: {
			ElectPopup,
			HeaderBar,
			btnlogin
		},
		props: {
			isIndex: {
				type: Boolean,
				default: () => false
			},
			userId: {
				type: String,
				default: () => ''
			},
			shareId: {
				type: String,
				default: () => ''
			}
		},
		data() {
			return {
				visible: true,
				info: [],
				form: {
					nickname: '',
					identity_id: '',
					company: ''
				},
				identity: {
					name: '',
					id: ''
				},
				template: {},
				cardStyleInfo: '',
				list: [],
				zheshow: false,
				code: '',
				userInfo: {},
				circle_id: 0 //圈子
			}
		},

		onLoad(e) {
			if(e.circle_id > 0) {
				this.circle_id = e.circle_id
			}
			let token = uni.getStorageSync('token')
			if (token) {
				InformationBusinessCardList().then(res => {
					this.list = res.data
				})
				InformationUserInfo().then(res => {
					this.userInfo = res.data
				})
			}

		},
		methods: {
			/**
			 * @param {Number} type 1 保存成功
			 */
			toLoading(type = 0) {
				if (this.isIndex) {
					this.$store.commit('setIsRefresh', true)
					this.$store.commit('setIsCircleRefresh', true)
					uni.reLaunch({
						url: "/pages/loading/loading"
					})
				} else {
					if(type === 1) {
						uni.showModal({
							title: '',
							content: '是否加入该圈子？',
							showCancel: true,
							cancelText: '取消',
							confirmText: '去加入',
							confirmColor: '#12B475',
							success: res => {
								if (res.confirm) {
									console.log('用户点击确认按钮');
									if(this.circle_id > 0) {
										uni.redirectTo({
											url:'/pages/index/addCard?id=' + this.circle_id
										})
									} else {
										uni.navigateBack()
									}
								} else if (res.cancel) {
									console.log('用户点击取消按钮');
									uni.navigateBack()
								}
							}
						});
					} else {
						uni.navigateBack()
					}
					
				}
			},
			openLogin() {
				console.log('openLogin', openLogin)
				this.$refs.btnlogin.show()
			},
			submitLogin(e) {
				uni.login({
					provider: 'weixin',
					success: loginRes => {
						console.log(loginRes);
						this.code = loginRes.code
						let data = {
							code: this.code,
							...e,
						}
						if (this.userId) {
							data['share_userId'] = this.userId
						}
						if (this.shareId) {
							data['login_share_business_card_id'] = this.shareId
						}
						console.log('onLoa=>', data)
						uni.showLoading()
						miniLogin(data).then(res => {
							uni.setStorageSync("token", res.data.token)
							this.httpAdd()
						})
					}
				});

			},
			open() {
				console.log('this.$refs.selectRef', this.$refs.selectRef)
				this.$refs.selectRef.show(this.info)
			},
			submit() {
				if (this.list.length === 0) {
					if (this.form.nickname === '') {
						uni.showToast({duration:3000,
							title: '请输入姓名！',
							icon: 'none'
						})
						return
					}
					if (this.form.nickname.length > 7) {
						uni.showToast({duration:3000,
							title: '姓名不能超过7个字符！',
							icon: 'none'
						})
						return
					}
				}

				// if (this.identity.name === '') {
				// 	uni.showToast({duration:3000,
				// 		title: '请选择领域！',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				// if (this.form.company === '') {
				// 	uni.showToast({duration:3000,
				// 		title: '请输入公司！',
				// 		icon: 'none'
				// 	})
				// 	return
				// }

				console.log('isIndex', this.isIndex)
				if (this.isIndex) {
					let token = uni.getStorageSync('token')
					console.log('token' + token)
					if (token) {
						this.httpAdd()
					} else {
						//this.$refs.btnlogin.show()
						uni.showLoading()
						InformationUserCodeLogin(data).then(res => {
							// uni.setStorageSync("token",res.data.token)
							// uni.reLaunch({
							// 	url:'/pages/loading/loading'
							// })
							if (res.data?.token) {
								uni.setStorageSync("token", res.data.token)
							}
							this.$store.commit('setIsRefresh', true)
							this.httpAdd()
						}).finally(err => {
							uni.hideLoading()
						})
					}

				} else {
					this.httpAdd()
				}

			},
			httpAdd() {

				let data = {
					// identity_id: this.identity.id,
					company: this.form.company
				}
				if (this.list.length === 0) {
					data['nickname'] = this.form.nickname
				}
				uni.showLoading()
				InformationEditBusinessCard(data).then(res => {
					//this.info = res.data
					// uni.showToast({duration:3000,
					// 	title:'领取成功',
					// 	icon:'none'
					// })
					// uni.navigateBack()
					this.getCardStyle(res.data)
				})
			},
			getCardStyle(user_id) {
				uni.showLoading()
				InformationUserBusinessCardHeadData({

					business_card_id: user_id
				}).then(res => {
					this.cardStyleInfo = res.data
					this.$refs.cardRef.show(this.cardStyleInfo.business_card_layout, this.cardStyleInfo.user, this
						.cardStyleInfo.user.user_img, this.userInfo)
					this.$nextTick(() => {
						this.setCardHttp()
					})
				})
			},
			setCardStyle() {
				this.$nextTick(() => {

				})
			},
			async setCardHttp() {
				uni.showLoading()
				this.$refs.cardRef.submit().then(data => {
					ossUpload(data).then(res => {
						let business_card_img = res.url
						let data = {
							style_id: this.cardStyleInfo.style_id,
							background_id: this.cardStyleInfo.background_id,
							user_img: this.cardStyleInfo.user.user_img,
							business_card_img,
							business_card_id: this.cardStyleInfo.business_card_id
						}
					
						uni.showLoading()
						InformationStyleSaving(data).then(res => {
							if (!this.cardStyleInfo.intercept) {
								this.template = {
									css: {
										// 根节点若无尺寸，自动获取父级节点
										width: '333rpx',
										height: '266.4rpx'
									},
									views: [
										//底图
										{
											type: 'image',
											src: this.cardStyleInfo.Template_img,
											css: {
												width: '100%',
												height: '100%',
												top: "0",
												right: "0",
												position: "absolute",
												zIndex: '5',
											}
										},
										//名片
										{
											type: 'image',
											src: business_card_img,
											css: {
												width: '333rpx',
												top: "0",
												right: "0",
												position: "absolute",
												zIndex: '4',
											}
										}
									]
								}
								this.$nextTick(() => {
									this.setShareCardHttp()
								})

							} else {
								uni.showToast({duration:3000,
									title: '保存成功',
									icon: 'none'
								})
								setTimeout(() => {
									this.$store.commit('setIsRefresh', true)
									this.toLoading(1)
								}, 1500)

							}


						})
					}).catch(err => {
						// uni.showToast({duration:3000,
						// 	title: '上传失败！',
						// 	icon: 'none'
						// })
						setTimeout(() => {
							this.toLoading()
						}, 1500)
					})
				}).catch(err => {
					console.log('err', err)
					// uni.showToast({duration:3000,
					// 	title: "未能生成，请重新保存!",
					// 	icon: 'none'
					// })
					setTimeout(() => {
						this.toLoading()
					}, 1500)
				})
			},
			async setShareCardHttp() {
				this.$refs.painterRef.canvasToTempFilePathSync({
					fileType: "jpg",
					// 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
					pathType: 'url',
					quality: 1,
					success: (res) => {
						console.log(res.tempFilePath);

						// 非H5 保存到相册
						// H5 提示用户长按图另存
						ossUpload(res.tempFilePath).then(res => {
							let business_card_img = res.url
							let data = {
								share_id: this.cardStyleInfo.share_id,
								share_img: business_card_img,
								business_card_id: this.cardStyleInfo.business_card_id,
								intercept: this.cardStyleInfo.intercept,
								share_title: this.cardStyleInfo.share_title,
							}
							console.log('data', data)
							uni.showLoading()
							InformationShareStylesSaving(data).then(res => {
								uni.showToast({duration:3000,
									title: '保存成功',
									icon: 'none'
								})
								this.$store.commit('setIsRefresh', true)
								setTimeout(() => {
									this.$store.dispatch('getShare')
									this.toLoading(1)
								}, 1500)


							})
						}).catch(err => {
							setTimeout(() => {
								this.toLoading()
							}, 1500)
						})
					},
				});
			}
		}
	}
</script>

<style lang="scss">
	image {
		width: 100%;
		height: 100%;
	}

	.bgcard {
		width: 100%;
	}

	.titlecard {
		padding: 30rpx 0 50rpx;
		width: 100%;
		text-align: center;
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #131313;
	}

	.formcard {
		width: 606rpx;
		margin: 0 auto;

		.form-listcard {
			height: 90rpx;
			background: #F6F7F8;
			border-radius: 20rpx;
			margin-bottom: 24rpx;
			display: flex;
			padding: 0 21rpx;
			align-items: center;
			box-sizing: border-box;

			.form-list-inputcard {
				flex: 1;
				min-width: 0;
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #BBBBBB;

				input {
					width: 100%;
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #000;
				}

				.accard {
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #BBBBBB;
				}
			}

			image {
				width: 28rpx;
				height: 18rpx;
			}
		}
	}

	.btnsCard {
		width: 577rpx;
		height: 86rpx;
		background: #23B97F;
		border-radius: 43rpx;
		margin: 0 auto;
		display: flex;
		justify-content: center;
		align-items: center;
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #FFFFFF;
		margin-top: 70rpx;
	}
</style>